package com.hsd.znsh.utils;


import com.hsd.znsh.entity.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class SecurityUtil {

    public static boolean hasRole(String role){
        List<String> list=getRole();
        for(String string:list){
            if(string.trim().equalsIgnoreCase(role)) return true;
        }
        return false;
    }

    public static boolean hasRole(String role,Authentication authentication){
        List<String> list=getRole(authentication);
        for(String string:list){
            if(string.trim().equalsIgnoreCase(role)) return true;
        }
        return false;
    }

    public static List<String> getRole(Authentication authentication){
        Iterator iterator=authentication.getAuthorities().iterator();
        List<String> list=new ArrayList<>();
        while(iterator.hasNext()){
            SimpleGrantedAuthority simpleGrantedAuthority=(SimpleGrantedAuthority)iterator.next();
            list.add(simpleGrantedAuthority.getAuthority());
        }
        return list;
    }

   public static List<String> getRole(){
       Authentication authentication=getAuthentication();
       Iterator iterator=authentication.getAuthorities().iterator();
       List<String> list=new ArrayList<>();
       while(iterator.hasNext()){
           SimpleGrantedAuthority simpleGrantedAuthority=(SimpleGrantedAuthority)iterator.next();
           list.add(simpleGrantedAuthority.getAuthority());
       }
       return list;
   }

    public static String getUsername( ){
        Authentication authentication=getAuthentication();
        return authentication.getName();
    }

    public static Integer getUserId( ){
        return getUser().getId();
    }

    public static User getUser( ){
        Authentication authentication=getAuthentication();
        User user=(User)authentication.getPrincipal();
        return user;
    }

   private static Authentication getAuthentication(){
       SecurityContext context= SecurityContextHolder.getContext();
       return context.getAuthentication();
   }

}
